#include "filewidget.h"
#include "ui_filewidget.h"
#include <QFileDialog>
#include<QTime>
#include<QCoreApplication>
#include<QDebug>

#include<QFileInfo>
#include<QDir>
#include<QFileInfoList>

#include<QImage>
filewidget::filewidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::filewidget)
{
    ui->setupUi(this);

    packageSize = 64;
    delayTime = 1;


    //获取字体文件路径
    connect(ui->pushButton,&QPushButton::clicked,this,[=](){
        QString filename = QFileDialog::getOpenFileName(this,"Open font file");
        ui->lineEdit->setText(filename);
    });
    //获取固件文件路径
    connect(ui->pushButton_3,&QPushButton::clicked,this,[=](){
        QString filename = QFileDialog::getOpenFileName(this,"Open font file");
        ui->lineEdit_2->setText(filename);
    });
    //获取文件夹
    connect(ui->pushButton_5,&QPushButton::clicked,this,[=](){
        QString filename = QFileDialog::getExistingDirectory(this,"Open img dir");
        ui->lineEdit_3->setText(filename);
    });
    //获取文件夹
    connect(ui->pushButton_7,&QPushButton::clicked,this,[=](){
        QString filename = QFileDialog::getExistingDirectory(this,"Open img dir");
        ui->lineEdit_4->setText(filename);
    });
    //发送字体数据
    connect(ui->pushButton_2,&QPushButton::clicked,this,&filewidget::SendFontFile);
    //发送固件数据
    connect(ui->pushButton_4,&QPushButton::clicked,this,&filewidget::SendFirmwareFile);
    //发送动画数据
    connect(ui->pushButton_6,&QPushButton::clicked,this,&filewidget::SendAnimationFile);
    //发送待机图片
    connect(ui->pushButton_8,&QPushButton::clicked,this,&filewidget::SendImgFile);

}

filewidget::~filewidget()
{
    delete ui;
}

void filewidget::getCfg(){
    packageSize = ui->comboBox_2->currentText().toInt();
    delayTime   = ui->comboBox_3->currentText().toInt();
}


/*发送字体文件*/
void filewidget::SendFontFile(){

    getCfg();
    QString filename = ui->lineEdit->text();
    QFileInfo base(filename);

    int filesize = base.size();


    uint8_t func2;
    QString fonttype = ui->comboBox->currentText();
    if( QString::compare(fonttype,"大") == 0)
       func2 = 0x01;
    else if( QString::compare(fonttype,"中") == 0)
       func2 = 0x02;
    else
       func2 = 0x03;
    SendCMD(0x1A,func2,0xff,filesize,0,0);


    QTime _CMDTimer = QTime::currentTime().addMSecs(5000);
    while( QTime::currentTime() < _CMDTimer )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 5);


    qDebug() << delayTime;
    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    ui->progressBar->setRange(0,filesize);
    ui->progressBar->setValue(0);
    char databuff[1024];
    int sendSize = 0;
    while(1){
       qint64 realSize = file.read(databuff,packageSize);
       sendSize += realSize;
       emit sendData(databuff,packageSize);   //发送数据
       ui->progressBar->setValue(sendSize);
       if( realSize < packageSize)
           break;
       //延时 非阻塞
       QTime _Timer = QTime::currentTime().addMSecs(delayTime);
       while( QTime::currentTime() < _Timer )
           QCoreApplication::processEvents(QEventLoop::AllEvents, 5);
    }
    qDebug() << "文件大小 "<<  base.size();
    qDebug() << "发送大小 " << sendSize;
    file.close();

}


void filewidget::SendFirmwareFile(){

}

//获取文件路径
QVector<QString> calculateFolderFileList(const QString &path) {
    QDir dir(path);
    qint64 size = 0;
    QVector<QString> filelist;
    // 获取文件夹中所有文件和子文件夹
    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    // 遍历并累计大小
    for (const QFileInfo &fileInfo : fileInfoList) {
        if (fileInfo.isFile()) {
            filelist.append(fileInfo.path() +'/' + fileInfo.fileName());
           // size += 1;//fileInfo.size(); // 对于文件，直接加上文件大小
            qDebug() << fileInfo.path() +'/' + fileInfo.fileName();
        } else if (fileInfo.isDir()) {
        ;//    size += calculateFolderSize(fileInfo.absoluteFilePath()); // 对于子文件夹，递归调用
        }
    }

    return filelist;
}
//发送动画数据
void filewidget::SendAnimationFile(){
    getCfg();
    QVector<QString> filepath = calculateFolderFileList(ui->lineEdit_3->text());
    SendCMD(0x1A,0x05,0xff,filepath.size(),0,0);
    QTime _CMDTimer = QTime::currentTime().addMSecs(55000);//65000
    while( QTime::currentTime() < _CMDTimer )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 5);

    uint16_t imgbuf[32];
    uint16_t len = 0;
    int filesize = filepath.size() * (172*320*2);
    int sendSize = 0;
    ui->progressBar_3->setRange(0,filesize);
    ui->progressBar_3->setValue(0);
    for(int i = 0 ; i < filepath.size(); i++){
        QImage image;
        image.load(filepath.at(i));
        for(int j=0;j< 172;j++){
            for(int k=0;k<320;k++){
                QColor rgb = image.pixelColor(k,j);
                int r,g,b;
                rgb.getRgb(&r,&g,&b);
                uint16_t data = ((r & 0xF8) << 8) + ((g & 0xFC) << 3) + ((b & 0xF8) >> 3);
                data = ((data &0xff00) >> 8) + ((data &0x00ff) << 8);
                imgbuf[len] = data;
                len += 1;
                if( len == packageSize/2){
                    emit sendData((char *)imgbuf,packageSize);
                    len = 0;
                    sendSize += packageSize;
                    ui->progressBar_3->setValue(sendSize);
                    //延时 非阻塞
                    QTime _Timer = QTime::currentTime().addMSecs(delayTime);
                    while( QTime::currentTime() < _Timer )
                        QCoreApplication::processEvents(QEventLoop::AllEvents, 5);
                }
            }
        }
    }

}
void filewidget::SendImgFile(){
    getCfg();
    QVector<QString> filepath = calculateFolderFileList(ui->lineEdit_4->text());
    SendCMD(0x1A,0x06,0xff,filepath.size(),0,0);
    QTime _CMDTimer = QTime::currentTime().addMSecs(25000);//65000
    while( QTime::currentTime() < _CMDTimer )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 5);

    uint16_t imgbuf[32];
    uint16_t len = 0;
    int filesize = filepath.size() * (172*320*2);
    int sendSize = 0;
    ui->progressBar_4->setRange(0,filesize);
    ui->progressBar_4->setValue(0);
    for(int i = 0 ; i < filepath.size(); i++){
        QImage image;
        image.load(filepath.at(i));
        for(int j=0;j< 172;j++){
            for(int k=0;k<320;k++){
                QColor rgb = image.pixelColor(k,j);
                int r,g,b;
                rgb.getRgb(&r,&g,&b);
                uint16_t data = ((r & 0xF8) << 8) + ((g & 0xFC) << 3) + ((b & 0xF8) >> 3);
                data = ((data &0xff00) >> 8) + ((data &0x00ff) << 8);
                imgbuf[len] = data;
                len += 1;
                if( len == packageSize/2){
                    emit sendData((char *)imgbuf,packageSize);
                    len = 0;
                    sendSize += packageSize;
                    ui->progressBar_4->setValue(sendSize);
                    //延时 非阻塞
                    QTime _Timer = QTime::currentTime().addMSecs(delayTime);
                    while( QTime::currentTime() < _Timer )
                        QCoreApplication::processEvents(QEventLoop::AllEvents, 5);
                }
            }
        }
    }
}


void filewidget::SendCMD(uint8_t func1,uint8_t func2,uint8_t func3,int data1,int data2,int data3){
    uint8_t cmd[24];
    for(int i = 0 ;i< 24;i++){
        cmd[i] = 0xff;
    }
    cmd[0] = 0xEF;
    cmd[1] = func1;
    cmd[2] = func2;
    cmd[3] = func3;

    cmd[4] = (data1 & 0xff000000) >> 24;
    cmd[5] = (data1 & 0x00ff0000) >> 16;
    cmd[6] = (data1 & 0x0000ff00) >> 8;
    cmd[7] = (data1 & 0x000000ff);

    cmd[8] =  (data2 & 0xff000000) >> 24;
    cmd[9] =  (data2 & 0x00ff0000) >> 16;
    cmd[10] = (data2 & 0x0000ff00) >> 8;
    cmd[11] = (data2 & 0x000000ff);

    cmd[12] = (data3 & 0xff000000) >> 24;
    cmd[13] = (data3 & 0x00ff0000) >> 16;
    cmd[14] = (data3 & 0x0000ff00) >> 8;
    cmd[15] = (data3 & 0x000000ff);

    cmd[23] = 0xFE;
    emit sendData((char *)cmd,sizeof(cmd));   //发送命令
}
